package com.lms.netty.rpc.provider;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @Author: 李孟帅
 * @CreateTime: 2020-06-19 16:55
 * @Description:
 */
public class RpcNettyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String message = msg.toString();
        System.out.println("客户端消息msg:"+message);
        //客户端再调用服务器的api时，需要通过定义的协议通信
        //比如我么要求，每次发送消息需要以字符串开头 “HelloService#hello#msg”
        if (message.startsWith("HelloService#hello#")){
            String result = new HelloServiceImpl().hello(message.substring(message.lastIndexOf("#") + 1));
            System.out.println("发送："+result);
            ctx.writeAndFlush(result);
        }
        ctx.writeAndFlush("server");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("异常消息："+cause.getMessage());
        ctx.close();
    }

}
